package com.heima.article.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Async
public class ArticleTasks {

    @Autowired
    private Configuration configuration;

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private MinIOService minIOService;

    /**
     * 创建静态页面
     * @param article
     * @param content
     */
    public void createHtml(ApArticle article, String content) {
        try {
            // 加载模板
            Template template = configuration.getTemplate("article.ftl");
            // 定义数据模型
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            // 合并模板和数据模型
            StringWriter writer = new StringWriter();
            template.process(map, writer);
            // 获取数据流
            InputStream is = new ByteArrayInputStream(writer.toString().getBytes());
            // 上传到minio
            String url = minIOService.upload(article.getId() + ".html", is, "text/html");
            // System.out.println(url);
            // 更新数据库中的静态地址
            article.setStaticUrl(url);
            articleService.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
